package pct.manage;

import java.util.Map;


import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class AuthenticationInterceptor implements Interceptor {

	@Override
	public void destroy() {

	}

	@Override
	public void init() {

	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {

		Map<String, Object> session = actionInvocation.getInvocationContext()
				.getSession();

		purgeStaleTokens(session);

		StatusManager sm = (StatusManager) session.get("status");
		if (sm == null) {
			return Action.LOGIN;
		} else {
			Action action = (Action) actionInvocation.getAction();
			if (action instanceof AuthenticationAware) {
				((AuthenticationAware) action).setStatusManager(sm);
			}
		}

		return actionInvocation.invoke();
	}

	private void purgeStaleTokens(Map<String, Object> session) {

		Object userToken = session.get("status");
		if (!(userToken instanceof StatusManager))
			session.remove("status");

	}

}
